<template>
  <div class="file-upload">
    <el-upload
      ref="upload"
      :headers="headers"
      action="api/file/uploadPicture"
      :auto-upload="true"
      :file-list="fileList"
      :limit="limit"
      :class="{ hide: hideUpload }"
      :on-change="beforeAvatarUpload"
      :on-exceed="masterFileMax"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      list-type="picture-card"
      multiple
    >
      <i class="el-icon-plus"></i>
      <div slot="tip" class="form-tips" style="margin-top: 10px">
        <el-tag type="warning">最多上传25张，最大上传大小2MB</el-tag>
      </div>
    </el-upload>
    <el-dialog
      :visible.sync="dialogVisibles"
      append-to-body
      class="dialog1"
      width="45%"
    >
      <img :src="dialogImageUrl" alt="" class="ims">
    </el-dialog>
  </div>
</template>

<script>
import store from '@/store'
export default {
  data () {
    return {
      headers: {
        token: store.state.user.userInfo.token
      },
      backendImageList: [], // 存储后端返回的图片地址的数组
      dialogImageUrl: '', // 浏览图片的路径
      fileList: [], // 本地图片列表
      imgs: [],
      limit: 25, // 上传图片的数量
      dialogVisibles: false, // 控制浏览图片的对话框显示隐藏
      hideUpload: false, // 判断是否隐藏上传按钮
      isAdd: true, // 判断对应的操作
      construction: {
        images: [],
        addImages: [],
        delImages: []
      }
    }
  },
  methods: {
    beforeAvatarUpload (file, fileList) {
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return
      }

      // 只有在 auto-upload 为 false 时才将文件对象添加到 fileList
      if (!this.autoUpload) {
        // this.fileList.push(file)
      }

      // 达到限制上传图片，隐藏上传按钮
      this.hideUpload = this.fileList.length >= this.limit

      // // 如果 auto-upload 为 false，手动触发上传
      // if (!this.autoUpload) {
      //   this.$refs.upload.submit()
      // }
    },
    handleRemove (file, fileList) {
      this.hideUpload = fileList.length >= this.limit
      console.log(this.fileList)
      if (this.isAdd) {
        const reader = new FileReader()
        reader.readAsDataURL(file.raw)
        reader.onload = (e) => {
          const index = this.construction.images.indexOf(e.target.result)
          if (index !== -1) {
            this.construction.images.splice(index, 1)
          }
        }
      } else {
        if (file.raw) {
          const reader = new FileReader()
          reader.readAsDataURL(file.raw)
          reader.onload = (e) => {
            const index = this.construction.addImages.indexOf(e.target.result)
            if (index !== -1) {
              this.construction.addImages.splice(index, 1)
            }
          }
        } else {
          this.construction.delImages.push(file.url)
        }
      }
      // 使用 file.response 获取后端返回的文件信息
      const fileUrl = file.response && file.response.data && file.response.data.path

      // 查找并移除 backendImageList 中的对应图片地址
      // 【注意】这里的删除只是不提交该图片地址，事实上该图片已经存入了
      if (fileUrl) {
        const indexInBackendList = this.backendImageList.findIndex(item => item === fileUrl)
        if (indexInBackendList !== -1) {
          this.backendImageList.splice(indexInBackendList, 1)
        }
      }
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisibles = true
      // console.log(this.fileList)
    },
    masterFileMax (files, fileList) {
      if (files.length + fileList.length > this.limit) {
        this.$message.warning(`请最多上传 ${this.limit} 个文件。`)
      }
      // console.log(this.fileList)
    },

    resetImages () {
      this.fileList = []
      this.imgs = []
      this.backendImageList = [] // 添加这行代码
    },
    getImages () {
      console.log(this.fileList)
      return this.backendImageList
    },
    handleSuccess (response) {
      if (response.code === 1) {
        this.$message.success('文件上传成功')
        const uploadedFile = response.data.path // 后端返回的图片地址
        this.backendImageList.push(uploadedFile) // 添加到后端图片地址列表
        // console.log(this.fileList)
        // console.log(this.backendImageList)
      } else {
        this.$message.error('文件上传失败')
      }
    }

  }
}
</script>
